#include <iostream>
#include <mutex>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#define ERR_EXIT(m)\
do\
{\
    perror(m);\
    exit(EXIT_FAILURE);\
} while (0);
// pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
std::mutex mtx;
int num = 1200;
void* pthread_func(void* argv){
    int t = 0;
    pthread_t pid=pthread_self();
    while(1){
        // pthread_mutex_lock(&lock);
        // mtx.lock();
        std::lock_guard<std::mutex>lock(mtx);
        if(num > 0){
            t++;
            usleep(1000);
            num-=1;
            printf("i am %ld,now num is %d,t=%d\n",(long int)pid,num,t);
            // pthread_mutex_unlock(&lock);
            // mtx.unlock();
        }
        else {
            // pthread_mutex_unlock(&lock);
            // mtx.unlock();
            break;
        }
    }
    printf("OVER:i am %ld,now num is %d,t=%d\n",(long int)pid,num,t);
    return nullptr;
}

int main(){
    clock_t start=clock();
    pthread_t tid1;
    pthread_t tid2;
    if(pthread_create(&tid1,nullptr,pthread_func,nullptr) != 0)
    ERR_EXIT("pthread_create");
    if(pthread_create(&tid2,nullptr,pthread_func,nullptr) != 0)
    ERR_EXIT("pthread_create");
    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    clock_t end=clock();
    printf("################\n");
    printf("TOTAL TIME CONSUME: %ld\n",(long int)end-start);
    // if (pthread_mutex_destroy(&lock) != 0)
    // {
    //     ERR_EXIT("pthread_mutex_destroy");
    // }
}
//unlock time:22080
//lock time:34797
